package models

import (
	"gorm.io/gorm"
)

type News struct {
	gorm.Model
	Title    string `gorm:"type:varchar(30);not null"`
	TypeId   int    `gorm:"type:int(3);not null"`
	Images   string `gorm:"type:varchar(255);not null"`
	Num      int    `gorm:"type:int(3);not null"`
	UserName string `gorm:"type:varchar(20);not null"`
	Status   string `gorm:"type:varchar(10);not null"`
}

type NewsData struct {
	News
	TypeName string
}

func (n *News) Create() error {
	return DB.Create(&n).Error
}

func (n *News) GetNewsById() error {
	return DB.Where("id=?", n.ID).Limit(1).Find(&n).Error
}

func (n *News) Del() error {
	return DB.Delete(&n).Error
}

func (n *News) List(id, page, pageSize int) (list []NewsData, err error) {
	query := DB.Debug()

	if id != 0 {
		query = query.Where("id=?", n.ID)
	}

	err = DB.Table("news").
		Select("news.*,news_types.name as type_name").
		Scopes(Paginate(page, pageSize)).
		Joins("left join news_types on news.type_id=news_types.id").
		Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 5
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
